package cn.xz.gobang.activity

import android.graphics.Color
import android.os.CountDownTimer
import androidx.core.view.isVisible
import androidx.recyclerview.widget.GridLayoutManager
import cn.xz.gobang.R
import cn.xz.gobang.adapter.ChessPAdapter
import cn.xz.gobang.base.BaseActivity
import cn.xz.gobang.bean.*
import cn.xz.gobang.databinding.ActivitySingleBinding
import cn.xz.gobang.dialog.BackDialog
import cn.xz.gobang.dialog.StartPkDialog
import cn.xz.gobang.dialog.WinDialog
import cn.xz.gobang.net.OkHttpUtil
import cn.xz.gobang.net.OkHttpUtil.HttpCallBack
import cn.xz.gobang.service.ServerManager
import cn.xz.gobang.service.ServerUtils
import cn.xz.gobang.util.*
import com.yanzhenjie.andserver.Server
import java.util.*


/**
 * 多人对局*/
class SingleActivity: BaseActivity<ActivitySingleBinding>(R.layout.activity_single) {

    private var chessPAdapter: ChessPAdapter? = null //棋盘适配器
    private var mType = true //是否是黑棋(0)，房主
    private var nowDown = true //当前下棋者 true 黑棋
    private var mClickData: ArrayList<ClickData> = arrayListOf() //已下棋子集合
    private var mClick: ChessPData? = null //当前下的棋子
    private var mIndex: Int = -1 //当前下的棋子的下标
    private var timer: Timer? = null //定时器
    private var hasWin = false //当前是否有赢家(游戏结束)
    private var mZDFinish = false //我主动半路退出
    private var mZDWin = false //因为对方退出我赢的
    private var mDownTimer = 60 //倒计时
    private var mCountDownTime: CountDownTimer? = null //定时器

    override fun initData() {
        //我是不是房主，看我从哪里跳过来的，如果是邀请我就是房主
        mType = intent.getBooleanExtra(CommonLib.JUMP_TYPE,true)
        //先设置好棋盘
        setP()
        //增加我的对局数，显示对战弹窗
        getSingle()
        //获取自己的数据
        getMine()
        //是否显示对方数据
        showData()
    }

    private fun getMine(){
        mDataBind.tvMineName.post {
            mDataBind.tvMineName.text = CommonLib.UserIP
            mDataBind.tvMineDj.text = SessionUtils.getInt(SessionUtils.USER_PK_NUM,0).toString()
            val mD = GetMyDataUtil.getNum(SessionUtils.getInt(SessionUtils.USER_GET_NUM,0))
            mDataBind.ivMineJb.setImageDrawable(mD.userPic)
            mDataBind.tvMineDw.text = mD.userDW
            mDataBind.tvMineDw.setTextColor(Color.parseColor(mD.userColor!!))
        }
    }

    //加入房间
    private fun getSingle(){
        //增加我的对局数
        SessionUtils.commitInt(SessionUtils.USER_PK_NUM,SessionUtils.getInt(SessionUtils.USER_PK_NUM,0) + 1)
        setPKData()
        StartPkDialog.newInstance().show(this@SingleActivity.supportFragmentManager,"StartPkDialog")
        //开启定时器，定时获取数据
        startTime()
    }


    //开游戏，开始定时
    private fun startTime(){
        timer = Timer()
        val timerTask: TimerTask = object : TimerTask() {
            override fun run() {
                if (chessPAdapter != null){
                    queryRoom()
                }
            }
        }
        timer?.schedule(timerTask, 0, 1000) //开启定时
    }

    //查询当前下棋数据
    private fun queryRoom(){
        //随便找一个人的数据查询就行，他们都是一致的
        val OtherIp = CommonLib.mFriends[0]
        OkHttpUtil.toGet("http://${OtherIp}:8080${CommonLib.GET_ALL_USER}",object : OkHttpUtil.RequestSuccess<RoomSingle> {
            override fun success(bean: RoomSingle?) {
                if (bean != null){
                    //当前房间人数，防止对面人数
                    if (bean.num > 1){
                        //判断当前谁下棋
                        mDataBind.clMineTime.post {
                            if (bean.nowDown){
                                //我是黑棋
                                if (mType){
                                    //显示我的倒计时,隐藏对方倒计时
                                    showMineTime()
                                }else{
                                    //显示对方倒计时，隐藏我的倒计时以及点击操作
                                    shoeOtherTime()
                                }
                            }else{
                                //白旗
                                if (mType){
                                    //我是黑棋，显示对方倒计时，隐藏我的倒计时
                                    shoeOtherTime()
                                }else{
                                    //我是白旗，显示我的倒计时，隐藏对方倒计时
                                    showMineTime()
                                }
                            }
                            //开始倒计时
                            mDownTimer--
                            //如果倒计时结束，判断谁赢谁输
                            if (mDownTimer <= 0){
                                //有获胜方之后显示蒙层，禁止点击，停止定时器
                                var winType = 0
                                if (bean.nowDown){
                                    //当前下方是黑棋
                                    winType = 1
                                }
                                showWinDialog(winType)
                            }
                        }

                        //查询已提交的棋子数据，是否获胜
                        mClickData.clear()
                        mClickData.addAll(bean.mClickData)
                        //更新界面
                        runOnUiThread {
                            val mData = chessPAdapter!!.data
                            mClickData.forEach {
                                if (mData[it.position].type != it.type){
                                    mData[it.position].type = it.type
                                    chessPAdapter!!.notifyItemChanged(it.position)
                                }
                            }
                        }
                        //判断输赢 1.当前已下集合 2.全部集合 3.回调
                        ClickWinUtil.to(mClickData, chessPAdapter!!.data,object: ClickWinUtil.OnClickWinListener{
                            override fun success(type: Int) {
                                //有获胜方之后显示蒙层，禁止点击，停止定时器
                                showWinDialog(type)
                            }
                        })
                        CommonLib.mData = bean
                    }else{
                        mZDWin = true
                        var mTypeB = 1
                        if (mType){
                            mTypeB = 0
                        }
                        showWinDialog(mTypeB)
                    }
                }
            }

            override fun error() {

            }

        },RoomSingle::class.java)
    }

    override fun initEvent() {
        mDataBind.viewUnClick.setOnClickListener {  }
        //确认按钮
        mDataBind.llcOn.setOnClickListener {
            if (mClick != null && mIndex != -1) {
                //拿到棋子数据，进行数据更新
                val mRoomSingle = CommonLib.mData
                //我下完了，对方下
                nowDown = !nowDown
                mRoomSingle.nowDown = nowDown
                mRoomSingle.mClickData.clear()
                val mBody = mClickData
                mBody.add(ClickData(mClick!!.type, mIndex))
                mRoomSingle.mClickData.addAll(mBody)

                CommonLib.mData = mRoomSingle
                mDataBind.llcClick.post {
                    //mDataBind.viewUnClick.gone()
                    mDataBind.llcClick.gone()
                }
            }
        }
        //取消按钮
        mDataBind.llcCancel.setOnClickListener {
            val mData = chessPAdapter!!.data
            mData[mIndex].type = -1
            chessPAdapter!!.notifyItemChanged(mIndex)
            mDataBind.viewUnClick.gone()
            mDataBind.llcClick.gone()
        }
        //退出
        mDataBind.llcBack.setOnClickListener {
            //当前没有获胜者，说明在游戏进行中，弹窗提示，如果还继续则扣分
            if (!hasWin){
                BackDialog.newInstance(object : BackDialog.OnClickListener{
                    override fun onYes() {
                        mZDFinish = true
                        //减积分
                        GetDataUtils.setUserPart(false,2)
                        finish()
                    }
                }).show(this@SingleActivity.supportFragmentManager,"BackDialog1234")
            }else{
                finish()
            }
        }

    }

    //设置棋盘
    private fun setP(){
        mDataBind.rvQp.post {
            val ms = object : GridLayoutManager(this, 15) {
                //禁止上下滑动
                override fun canScrollVertically(): Boolean {
                    return false
                }
            }
            mDataBind.rvQp.layoutManager = ms
            chessPAdapter = ChessPAdapter()
            mDataBind.rvQp.adapter = chessPAdapter
            val mChess: ArrayList<ChessPData> = arrayListOf()
            for (i in 1..225){
                mChess.add(ChessPData())
            }
            chessPAdapter?.setList(mChess)
            chessPAdapter?.setOnItemClickListener { adapter, view, position ->
                val mData = chessPAdapter!!.data
                mClick = mData[position]
                if (mClick != null){
                    //判断当前选位置是否有棋子,有棋子了，显示音效
                    if (mClick!!.type == -1){
                        var clickType = 1
                        if (mType){
                            clickType = 0
                        }
                        mClick!!.type = clickType
                        chessPAdapter!!.notifyItemChanged(position)
                        mIndex = position
                        //已经落棋，禁止点击，去点落棋还是取消
                        mDataBind.viewUnClick.visible()
                        mDataBind.llcClick.visible()
                    }else{
                        ToastUtil.show("已有棋子")
                    }
                }
            }
        }
    }



    private fun cancelTime(){
        if (timer != null){
            timer!!.cancel()
            timer = null
        }
    }

    private fun showData(){
        mDataBind.tvPkName.text =  CommonLib.mFriends[0]
        mDataBind.clPk.post {
            if (!SessionUtils.getBoolean(SessionUtils.SHOW_PK_DATA,true)){
                mDataBind.clPk.invisible()
                mDataBind.clMine.invisible()
            }
        }
    }

    //设置对方数据
    private fun setPKData(){
        mDataBind.tvPkName.post {
            mDataBind.tvPkName.text =  CommonLib.mFriends[0]
        }
    }

    //显示我方倒计时
    private fun showMineTime(){
        if (mDataBind.clMineTime.isGone){
            mDownTimer = 60
            mDataBind.clMineTime.visible()
            mDataBind.viewUnClick.gone()
            mDataBind.clPkTime.gone()
        }
        mDataBind.tvMineTime.text = mDownTimer.toString()
    }

    //显示对方倒计时
    private fun shoeOtherTime(){
        if (mDataBind.clMineTime.isVisible){
            mDownTimer = 60
            mDataBind.clMineTime.gone()
            mDataBind.viewUnClick.visible()
            mDataBind.clPkTime.visible()
        }
        mDataBind.tvPkTime.text = mDownTimer.toString()
    }

    //有获胜方，对应控件显示隐藏
    private fun hideView(){
        //有胜利方，停止定时器
        cancelTime()
        //有获胜方
        hasWin = true
        //有获胜方之后显示蒙层，禁止点击
        mDataBind.viewUnClick.post {
            //隐藏操作按钮
            mDataBind.llcClick.gone()
            //禁止点击蒙层
            mDataBind.viewUnClick.visible()
            //隐藏倒计时
            mDataBind.clMineTime.gone()
            mDataBind.clPkTime.gone()
        }
    }

    //获取弹窗
    private fun showWinDialog(winType: Int){
        //有获胜方之后显示蒙层，禁止点击
        hideView()
        var mTypeB = 1
        if (mType){
            mTypeB = 0
        }
        WinDialog.newInstance(winType,mTypeB).show(this@SingleActivity.supportFragmentManager,"WinDialog123456")
    }


    override fun onDestroy() {
        super.onDestroy()
        cancelTime()
        if (mCountDownTime != null){
            mCountDownTime!!.cancel()
            mCountDownTime = null
        }
        //总人数减一
        val mRoomSingle = CommonLib.mData
        if (mRoomSingle.num - 1 > 0){
            mRoomSingle.num = mRoomSingle.num - 1
            CommonLib.mData = mRoomSingle
        }

        //关闭服务
        ServerUtils.stopServer()
    }

}